#include <stdio.h>
#include <stdlib.h>
#include "SqList.h"

// 初始化顺序表
SqList_p SqList_Init(int max_size, int extend_ratio)
{
    SqList_p sqlist = (SqList_p)malloc(sizeof(SqList_t));
    sqlist->size = 0;
    sqlist->arr = (int *)malloc(sizeof(int) * sqlist->extend_ratio);

    return sqlist;
}

// 数组扩容
void expand(SqList_p sqlist)
{
    sqlist->max_size *= sqlist->extend_ratio;
    int *newArr = (int *)calloc(sqlist->max_size, sizeof(int)); // 个数 大小
    for (int i = 0; i < sqlist->max_size; i++)
    {
        if (i < sqlist->size)
        {
            newArr[i] = sqlist->arr[i];
        }
    }
    free(sqlist->arr);
    sqlist->arr = newArr;
}

// 尾部添加
void push(SqList_p sqlist, int value)
{
    if (sqlist->size == sqlist->max_size)
    {
        expand(sqlist);
    }
    sqlist->arr[sqlist->size] = value;
    sqlist->size++;
}

// 指定位置删除
int delete(SqList_p sqlist, int index)
{
    if (index < 0 || index >= sqlist->size)
    {
        return -1;
    }
    for (int i = index; i < sqlist->size - 1; i++)
    {
        sqlist->arr[i] = sqlist->arr[i + 1];
    }
    return --sqlist->size;
}

// 尾部删除
int pop(SqList_p sqlist)
{
    if (sqlist->size == 0)
    {
        return -1;
    }
    return delete(sqlist, sqlist->size - 1);
}

// 析构函数
void delMyList(SqList_p sqlist)
{
    free(sqlist->arr);
    free(sqlist);
}

// 查找元素
int findIndex(SqList_p sqlist, int value)
{
    for (int i = 0; i < sqlist->size; i++)
    {
        if (sqlist->arr[i] == value)
        {
            return i;
        }
    }
    return -1;
}

// 打印顺序表
void print_SqList(SqList_p sqlist)
{
    for (int i = 0; i < sqlist->size; i++)
    {
        printf("%d ", sqlist->arr[i]);
    }
    printf("\n");
}